<template>
   <div class="tw-libwsreciver"
    :class="{[`x${this._uid}`]:true}"
    :style="style">
     {{wsname}}
   </div>
</template>

<script>
import props from './props'

export default {
  name: 'websock-reciver',

  props,

  data() {
    return {
      timeoutObj: null,
      ws: null
    }
  },

  computed: {
    style () {
      return {
        color: this.color,
        backgroundColor: this.bgColor
      }
    }
  },

  methods: {
    setStyle () {
      const style = `
        ::root.tw-libwsreciver {
          background-color: ${this.bgColor};
          color: ${this.color};
        }
      `
      this.addStyle(style)
    },

    addStyle (style) {
      this.$el.classList.add(`x${this._uid}`)
      const styleEl = document.getElementById(this._uid) || document.createElement('style')
      styleEl.id = this._uid
      styleEl.innerText = style.replace(/::root/gm, `.x${this._uid}`).replace(/\n/gm, '')

      document.head.appendChild(styleEl)
    },

    /**
     * 链接websocket服务器
     */
    initWebsoket () {
      if (this.ws) {
        this.ws.close()
      }
      if (!this.wsLink) {
        return
      }
      this.ws = new WebSocket(this.wsLink)
      let vm = this
      this.ws.onopen = function () {
        console.log('%c App connects to wsServer success.', 'color: green')
        vm.wsKeepConnect()
      }
      this.ws.onmessage = function (e) {
        vm.wsReset()
        console.log('from server: ' + e.data)
        // 排除控制器页面
        if (e.data) {
          vm.$router.push(e.data)
        }
      }
    },
    /**
     * 保持连接
     */
    wsKeepConnect () {
      let vm = this
      this.timeoutObj = setInterval(() => {
        if (vm.ws.readyState === 1) {
          // '请勿修改 HeartBeat 一词'
          vm.ws.send('HeartBeat')
        }
      }, parseInt(vm.timeout))
    },
    /**
     * 重置心跳确认包
     */
    wsReset () {
      window.clearInterval(this.timeoutObj)
      this.wsKeepConnect()
    },
  },
  beforeDestroy () {
    if (this.ws) {
      this.ws.close()
    }
    if (this.timeoutObj) {
      window.clearInterval(this.timeoutObj)
    }
  },

  mounted () {
    // this.setStyle()
    this.initWebsoket()
  },

  watch: {
    timeout () {
      if (this.ws) {
        this.ws.close()
      }
      if (this.timeoutObj) {
        window.clearInterval(this.timeoutObj)
      }
      this.initWebsoket()
    },

    // style: {
    //   deep: true,
    //   handler () {
    //     this.setStyle()
    //   }
    // }
  }
}
</script>

<style lang="scss">
  @import './css/index.scss';
</style>
